<template>
    <div class="edu-page-warp">
        <div class="edu-page-title">{{$t('message.filterCondition')}}</div>
        <el-card shadow="never" body-style="padding: 24px;">
            <el-form
                :model="queryParams"
                ref="queryParams"
                label-width="80px"
                class="bg-white pd-12px"
            >
                <el-row :gutter="20" style="height: 50px;">
                    <el-col :span="6">
                        <el-form-item label="模板类型:">
                            <el-select v-model="queryParams.type" filterable>
                                <el-option
                                    v-for="item in options.types"
                                    :key="item.id"
                                    :label="item.typeName"
                                    :value="item.id"
                                ></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="状态:">
                            <el-select v-model="queryParams.status">
                                <el-option
                                    v-for="item in options.status"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value"
                                ></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8" :offset="4">
                        <el-form-item class="float-right">
                            <el-button @click="reset">{{$t('message.reset')}}</el-button>
                            <el-button type="primary" @click="getWorkflows">{{$t('message.filter')}}</el-button>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
        </el-card>
        <div class="edu-page-title mg-top">{{$t('message.workflowList')}}</div>
        <el-card shadow="never" body-style="padding: 24px;">
            <div class="edu-opertion-bar">
                <div class="float-left">
                    <el-input
                        placeholder="模板名称"
                        v-model="queryParams.name"
                        prefix-icon="el-icon-search"
                        @keyup.enter.native="getWorkflows"
                    ></el-input>
                </div>
                <div class="float-right">
                    <el-button @click="deleteTemplates" v-if="false">{{$t('message.delete')}}</el-button>
                    <el-button @click="startTemplates">{{$t('message.enable')}}</el-button>
                    <el-button @click="stopTemplates">{{$t('message.disable')}}</el-button>
                    <el-button
                        @click="createWorkflowTemplate"
                        type="primary"
                        v-if="functions['add_workflow']"
                    >{{$t('message.add')}}</el-button>
                </div>
            </div>
            <el-table
                :data="workflows.list"
                size="mini"
                @selection-change="handleSelectionChange"
                stripe
                tooltip-effect="light"
            >
                <el-table-column type="selection" width="30"></el-table-column>
                <el-table-column type="index" width="55" label="序号" align="center"></el-table-column>
                <el-table-column label="模板名称" show-overflow-tooltip>
                    <template slot-scope="scope">{{scope.row.name}}</template>
                </el-table-column>
                <el-table-column label="模板类型" show-overflow-tooltip>
                    <template slot-scope="scope">{{scope.row.typeName}}</template>
                </el-table-column>
                <el-table-column label="培养层次" show-overflow-tooltip>
                    <template slot-scope="scope">{{scope.row.level}}</template>
                </el-table-column>
                <el-table-column label="部门" show-overflow-tooltip>
                    <template slot-scope="scope">
                        <span :title="scope.row.department">{{scope.row.department}}</span>
                    </template>
                </el-table-column>
                <el-table-column label="状态">
                    <template slot-scope="scope">
                        <span v-if="scope.row.status==2">待启用</span>
                        <span v-if="scope.row.status==1">已启用</span>
                    </template>
                </el-table-column>
                <el-table-column label="操作">
                    <template slot-scope="scope">
                        <el-button
                            type="text"
                            v-if="scope.row.status==2"
                            @click="startTemplate(scope.row)"
                            size="mini"
                        >启用</el-button>
                        <el-button
                            type="text"
                            v-if="scope.row.status==1"
                            @click="stopTemplate(scope.row)"
                            size="mini"
                        >停用</el-button>
                        <el-button
                            type="text"
                            @click="editTemplate(scope.row)"
                            v-if="functions['edit_workflow']"
                            size="mini"
                        >{{$t('message.edit')}}</el-button>
                        <el-button
                            type="text"
                            @click="deleteTemplate(scope.row)"
                            v-if="functions['delete_workflow']"
                            size="mini"
                        >{{$t('message.delete')}}</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div class="edu-pagination">
                <div class="float-right">
                    <el-pagination
                        @size-change="onPageSizeChange"
                        @current-change="onCurrentPageChange"
                        :current-page="queryParams.pageNum_"
                        :page-sizes="[20,50,100,500,1000]"
                        :page-size="queryParams.pageSize_"
                        layout="total, sizes, prev, pager, next, jumper"
                        :total="workflows.total_"
                        style="float: right;margin:10px 60px 0 0;"
                    ></el-pagination>
                </div>
            </div>
        </el-card>
    </div>
</template>
<script>
import WorkflowApi from "common/src/api/workflow";
import { queryDic } from "common/src/api/dictionary";
import { findAllDeptList } from "common/src/api/user";
export default {
    name: "Workflow",
    data() {
        return {
            options: {
                status: [
                    { label: "全部", value: 0 },
                    { label: "已启用", value: 1 },
                    { label: "待启用", value: 2 }
                ],
                types: [{ typeName: "全部", id: "" }]
            },
            queryParams: {
                name: "",
                type: "",
                status: 0,
                pageNum_: 1,
                pageSize_: 20
            },
            departments: [],
            workflows: [],
            selectionDatas: [],
            functions: {}
        };
    },
    created() {
        this.$store.getters.getFuncUnderPage(this.$route.path).then(funcs => {
            this.functions = funcs;
            console.log(funcs);
        });
    },
    mounted() {
        this.getOptions();
        this.getDepartments();
    },
    activated() {
        this.getWorkflows();
    },
    methods: {
        getOptions() {
            // 查询模板类型
            WorkflowApi.selectTemplateType().then(response => {
                if (response.code == 200) {
                    this.options.types = this.options.types.concat(
                        response.data
                    );
                }
            });
        },
        handleSelectionChange(val) {
            this.selectionDatas = val;
        },
        editTemplate(workflow) {
            this.$router.push({
                name: "updateWorkflow",
                params: { templateId: workflow.id }
            });
        },
        deleteTemplate(workflow) {
            this.$confirm('确认删除?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(_ => {
                WorkflowApi.deleteTemplate([workflow.id])
                .then(response => {
                        if (response.code == 200) {
                            this.$message({
                                type: "success",
                                message: "删除流程模板成功"
                            });

                            return true;
                        } else {
                            this.$message({
                                type: "error",
                                message: response.msg
                            });
                            return false;
                        }
                    }
                    // error => {
                    //     this.$message({
                    //         type: "error",
                    //         message: "删除流程模板失败！"
                    //     });
                    //     return false;
                    // }
                )
                .then(handleResult => {
                    if (handleResult) {
                        this.getWorkflows();
                    }
                });
            })
        },
        deleteTemplates() {
            let idArray = [];
            for (let workflow of this.selectionDatas) {
                idArray.push(workflow.id);
            }
            WorkflowApi.deleteTemplate(idArray)
                .then(
                    response => {
                        this.$message({
                            type: response.code == 200 ? "success" : "error",
                            message: response.msg
                        });
                        return response.code == 200;
                    },
                    error => {
                        this.$message({
                            type: "success",
                            message: "删除流程模板失败！"
                        });
                        return false;
                    }
                )
                .then(handleResult => {
                    if (handleResult) {
                        this.getWorkflows();
                    }
                });
        },
        startTemplate(workflow) {
            WorkflowApi.startTemplate([workflow.id])
                .then(
                    response => {
                        if (response.code == 200) {
                            this.$message({
                                type: "success",
                                message: "启用流程模板成功"
                            });
                            return true;
                        } else {
                            this.$message({
                                type: "error",
                                message: response.msg
                            });
                            return false;
                        }
                    },
                    error => {
                        this.$message({
                            type: "error",
                            message: "启用流程模板失败！"
                        });
                        return false;
                    }
                )
                .then(handleResult => {
                    if (handleResult) {
                        this.getWorkflows();
                    }
                });
        },
        switchToListData(workflows) {
            workflows.list.forEach(element => {
                // 培养层次
                let levels = element.listCultureLevel.map(item => {
                    return item.cultureLevelId;
                });
                element.level = levels.length > 0 ? levels.join(" | ") : "";
                // 部门
                let depNames = element.listDepartement.map(eleItem => {
                    let dep = this.departments.find(depItem => {
                        return eleItem.departmentId == depItem.deptCode;
                    });
                    return dep ? dep.deptName : "";
                });
                element.department =
                    depNames.length > 0 ? depNames.join(" | ") : "";
            });

            return workflows;
        },
        startTemplates(workflows) {
            let idArray = [];
            for (let workflow of this.selectionDatas) {
                if (workflow.status == 2) {
                    idArray.push(workflow.id);
                }
            }
            if (idArray.length == 0) {
                this.$message({
                    type: "warning",
                    message: "请选择数据（只有停用状态的模板才能够启用）!"
                });
                return;
            }
            WorkflowApi.startTemplate(idArray)
                .then(
                    response => {
                        this.$message({
                            type: response.code == 200 ? "success" : "error",
                            message: response.msg
                        });

                        return response.code == 200;
                    },
                    error => {
                        this.$message({
                            type: "error",
                            message: "启用流程模板失败！"
                        });
                        return false;
                    }
                )
                .then(handleResult => {
                    if (handleResult) {
                        this.getWorkflows();
                    }
                });
        },
        stopTemplate(workflow) {
            WorkflowApi.stopTemplate([workflow.id])
                .then(
                    response => {
                        if (response.code == 200) {
                            this.$message({
                                type: "success",
                                message: "停用流程模板成功"
                            });
                            return true;
                        } else {
                            this.$message({
                                type: "error",
                                message: response.msg
                            });
                            return false;
                        }
                    },
                    error => {
                        this.$message({
                            type: "error",
                            message: "停用流程模板失败！"
                        });
                        return false;
                    }
                )
                .then(handleResult => {
                    if (handleResult) {
                        this.getWorkflows();
                    }
                });
        },
        stopTemplates(workflows) {
            let idArray = [];
            for (let workflow of this.selectionDatas) {
                if (workflow.status == 1) {
                    idArray.push(workflow.id);
                }
            }
            if (idArray.length == 0) {
                this.$message({
                    type: "warning",
                    message: "请选择数据（只有启用状态的模板才能够停用）!"
                });
                return;
            }
            WorkflowApi.stopTemplate(idArray)
                .then(
                    response => {
                        this.$message({
                            type: response.code == 200 ? "success" : "error",
                            message: response.msg
                        });

                        return response.code == 200;
                    },
                    error => {
                        this.$message({
                            type: "error",
                            message: "停用流程模板失败！"
                        });
                        return false;
                    }
                )
                .then(handleResult => {
                    if (handleResult) {
                        this.getWorkflows();
                    }
                });
        },
        getWorkflows() {
            WorkflowApi.selectTemplate(this.queryParams, { dic: true })
                .then(response => {
                    if (response.code === 200) {
                        this.workflows = this.switchToListData(response.data);
                    } else {
                        throw response.msg;
                    }
                })
                .catch(error => {
                    this.$message({
                        type: "error",
                        message: "查询流程管理信息失败！"
                    });
                });
        },
        onPageSizeChange(size) {
            this.queryParams.pageSize_ = size;
            this.getWorkflows();
        },
        onCurrentPageChange(currentPage) {
            this.queryParams.pageNum_ = currentPage;
            this.getWorkflows();
        },
        reset() {
            this.queryParams.name = "";
            this.queryParams.type = "";
            this.queryParams.status = 0;
            this.queryParams.pageNum_ = 1;
            this.queryParams.pageSize_ = 20;
            this.getWorkflows();
        },
        createWorkflowTemplate() {
            this.$router.push("/createworkflow");
        },
        getDepartments() {
            return findAllDeptList().then(
                response => {
                    if (response.code == 200) {
                        this.departments = response.data;
                    }
                    return this.departments.length > 0;
                },
                error => {
                    return false;
                }
            );
        }
    }
};
</script>

